package com.ssy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ssy.entity.PageBean;
import com.ssy.entity.Student;
import com.ssy.entity.StudentQueryParam;
import com.ssy.mapper.StudentMapper;
import com.ssy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 分页查询
     */
    @Override
    public PageBean pgae(StudentQueryParam studentQueryParam) {
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());

        List<Student> empPage = studentMapper.page(studentQueryParam);
        Page<Student> p = (Page<Student>) empPage;

        return new PageBean(p.getTotal(), p.getResult());
    }

    /**
     * 添加学生
     */
    @Override
    public void save(Student student) {
        // 补全数据
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());

        studentMapper.save(student);
    }

    /**
     * 批量删除学生
     */
    @Override
    public void delete(List<Integer> ids) {
        studentMapper.delete(ids);
    }

    /**
     * 根据id查询学生信息
     */

    @Override
    public Student getById(Integer id) {
        return studentMapper.getById(id);
    }

    /**
     * 根据id修改学生信息
     */
    @Override
    public void update(Student student) {
        // 需添加修改时间\
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    /**
     * 违纪处理
     * @param id
     * @param score
     */
    @Override
    public void violation(Integer id, Integer score) {
        // 查询当前学生信息是否存在
        Student student = studentMapper.getById(id);
        if (student == null) {
            System.out.println("学生不存在");
        }

        // 业务处理
        Short violationCount = student.getViolationCount(); // 违纪次数
        Short violationScore = student.getViolationScore(); // 违纪扣分

        // 违纪次数 + 1
        student.setViolationCount((short) ((violationCount == null ? 0 : violationCount) + 1));
        // 违纪扣分累加
        student.setViolationScore((short) ((violationScore == null ? 0 : violationScore) + score));

        // 更新时间
        student.setUpdateTime(LocalDateTime.now());

        studentMapper.update(student);
    }
}
